package com.blog.personalblog.service.Impl;

import com.blog.personalblog.DTO.UserDto;
import com.blog.personalblog.VO.UserVo;
import com.blog.personalblog.consts.PropertiesConstant;
import com.blog.personalblog.entity.User;
import com.blog.personalblog.entity.response.ReturnCode;
import com.blog.personalblog.entity.response.ServiceResponse;
import com.blog.personalblog.mapper.UserMapper;
import com.blog.personalblog.service.UserService;
import com.blog.personalblog.util.MD5Util;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@Service
public class UserServiceImpl implements UserService {
    private static final Logger Logger = LogManager.getLogger(UserServiceImpl.class);
    private final UserMapper userMapper;

    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public ServiceResponse<List<User>> getAllUser() {
        Logger.info("Enter UserService getAllUser");
        try{
            List<User> users = userMapper.findAll();
            return new ServiceResponse<>(ReturnCode.Ok, PropertiesConstant.EMPTY_STRING,users);
        }catch (Exception e){
            Logger.error("Error getAllUser,e.getMessage：{},e.getStackTrace：{}",e.getMessage(),e.getStackTrace());
            return new ServiceResponse<>(ReturnCode.ErrOtherError,"获取用户失败",null);
        }
        finally {
            Logger.info("Leave  UserService getAllUser");
        }

    }

    @Override
    public ServiceResponse<Boolean> createUser(UserDto userDto) {
        Logger.info("Enter UserService createUser" + userDto.getUserName());
        try{
            List<User> users = userMapper.findAll();
            List<String> createdUser= new CopyOnWriteArrayList<>();
            users.stream().parallel().forEach(user -> {
                if (user.getUserName().equals(userDto.getUserName())){
                    createdUser.add(userDto.getUserName());
                }
            });
            if (createdUser.size() > 0){
                Logger.info("create user failed" + createdUser.stream().findFirst().get() + "用户已经存在了");
                return new ServiceResponse<>(ReturnCode.ErrOtherError, createdUser.stream().findFirst().get() + "用户已经存在了" ,false);
            }
            userDto.setPassWord(MD5Util.MD5(userDto.getPassWord()));
            User user =  ConvertToUser(userDto);
            if (user.getCreateTime() == null) user.setCreateTime(LocalDateTime.now());
            if (user.getUpdateTime() == null) user.setUpdateTime(LocalDateTime.now());
            if (user.getLastLoginTime() == null) user.setUpdateTime(LocalDateTime.now());
            boolean res =  userMapper.insertUser(user);
            if (res){
                return new ServiceResponse<>(ReturnCode.Ok, PropertiesConstant.EMPTY_STRING,true);
            }else {
                Logger.error("Error createUser");
                return new ServiceResponse<>(ReturnCode.ErrOtherError,"用户创建失败",false);
            }
        }catch (Exception e){
            Logger.error("Error createUser,e.getMessage：{},e.getStackTrace：{}",e.getMessage(),e.getStackTrace());
            return new ServiceResponse<>(ReturnCode.ErrOtherError,"用户创建失败",false);
        }
        finally {
            Logger.info("Leave  UserService createUser");
        }
    }

    @Override
    public ServiceResponse<Boolean> updateUser(UserDto userDto) {
        Logger.info("Enter UserService updateUser" + userDto.getUserName());
        try{
            User user =  ConvertToUser(userDto);
            user.setUpdateTime(LocalDateTime.now());
            boolean res =  userMapper.updateUser(user);
            if (res){
                return new ServiceResponse<>(ReturnCode.Ok, PropertiesConstant.EMPTY_STRING,true);
            }else {
                Logger.error("Error updateUser");
                return new ServiceResponse<>(ReturnCode.ErrOtherError,"用户更新失败",false);
            }
        }catch (Exception e){
            Logger.error("Error updateUser,e.getMessage：{},e.getStackTrace：{}",e.getMessage(),e.getStackTrace());
            return new ServiceResponse<>(ReturnCode.ErrOtherError,"用户更新失败",false);
        }
        finally {
            Logger.info("Leave  UserService updateUser");
        }
    }

    @Override
    public ServiceResponse<Boolean> deleteUser(int id) {
        Logger.info("Enter UserService deleteUser" + id);
        try{
            List<User> users = userMapper.findAll();
            List<String> deletedUser= new CopyOnWriteArrayList<>();
            users.stream().parallel().forEach(user -> {
                if (user.getId() == id){
                    deletedUser.add(user.getUserName());
                }
            });
            if (deletedUser.size() == 0){
                return new ServiceResponse<>(ReturnCode.ErrOtherError,"用户不存在",false);
            }
            int res =  userMapper.deleteUser(id);
            if (res != 1){
                Logger.error("Error deleteUser");
                return new ServiceResponse<>(ReturnCode.ErrOtherError,"用户删除失败",false);
            }else {
                return new ServiceResponse<>(ReturnCode.Ok, PropertiesConstant.EMPTY_STRING,true);
            }
        }catch (Exception e){
            Logger.error("Error deleteUser,e.getMessage：{},e.getStackTrace：{}",e.getMessage(),e.getStackTrace());
            return new ServiceResponse<>(ReturnCode.ErrOtherError,"用户删除失败",false);
        }
        finally {
            Logger.info("Leave  UserService deleteUser");
        }
    }

    private static User ConvertToUser(UserDto userDto){
        if (userDto == null) return null;
        User user = new User();
        user.setId(userDto.getId());
        user.setUserName(userDto.getUserName());
        user.setPassWord(userDto.getPassWord());
        user.setEmail(userDto.getEmail());
        user.setNickname(userDto.getNickname());
        user.setPhone(userDto.getPhone());
        user.setLastLoginTime(userDto.getLastLoginTime());
        return user;
    }
}
